package com.jiyun.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiyun.mapper.*;
import com.jiyun.model.*;
import com.jiyun.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/* *
 * @Author nxj
 * @Date 2023 08 2023/8/4 10 43
 * */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private RaceMapper raceMapper;

    @Autowired
    private TrainMapper trainMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QuizMapper quizMapper;

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private CatalogMapper catalogMapper;

    @Autowired
    private CatalogUserMapper catalogUserMapper;

    @Autowired
    private RaceUserMapper raceUserMapper;

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RaceInfoMapper raceInfoMapper;

    @Autowired
    private QuizPaperMapper quizPaperMapper;

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private PaperUserMapper paperUserMapper;

    @Autowired
    private RankingsMapper rankingsMapper;


    @Override
    public List<Long> showCount(Integer id) {
        List<Long> list = new ArrayList<>();
        List<Race> list2 = raceMapper.selectList(null);
        long b = 0;
        for (Race race : list2) {
            String[] split1 = race.getUid().split(",");
            for (String s : split1) {
                if (s.equals(id + "")) {
                    b = b + 1;
                }
            }
        }
        List<Train> list3 = trainMapper.selectList(null);
        List<Train> list4 = new ArrayList<>();
        long c = 0;
        for (Train train : list3) {
            String[] split2 = train.getUid().split(",");
            for (String s : split2) {
                if (s.equals(id + "")) {
                    c = c + 1;
                    list4.add(train);
                }
            }
        }
        long a = 0;
        for (Train train : list4) {
            if (!train.getCid().equals("")) {
                String[] split = train.getCid().split(",");
                a = split.length + a;
            }
        }
        list.clear();
        list.add(b);
        list.add(c);
        list.add(a);
        list.add((long) id);
        return list;
    }

    @Override
    public List<Course> courseList() {
        List<Course> list1 = new ArrayList<>();
        LambdaQueryWrapper<Course> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Course::getGood);
        List<Course> list = courseMapper.selectList(lambdaQueryWrapper);
        list1.clear();
        for (int i = 0; i < 3; i++) {
            list1.add(list.get(i));
        }
        for (Course course : list1) {
            Object o = redisTemplate.boundValueOps(course.getId() + "").get();
            if (o == null) {
                course.setTyped(0);
            } else {
                course.setTyped(1);
            }
        }
        return list1;
    }

    @Override
    public List<Course> courseListD() {
        List<Course> list1 = new ArrayList<>();
        LambdaQueryWrapper<Course> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Course::getCreateTime);
        List<Course> list = courseMapper.selectList(lambdaQueryWrapper);
        list1.clear();
        for (int i = 0; i < 3; i++) {
            list1.add(list.get(i));
        }
        for (Course course : list1) {
            Object o = redisTemplate.boundValueOps(course.getId() + "").get();
            if (o == null) {
                course.setTyped(0);
            } else {
                course.setTyped(1);
            }
            if (course.getId() > 9) {
                course.setTyped(1);
            }
        }
        return list1;
    }

    @Override
    public List<Train> trainList() {
        List<Train> list1 = new ArrayList<>();
        LambdaQueryWrapper<Train> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Train::getStarttime);
        List<Train> list = trainMapper.selectList(lambdaQueryWrapper);
        list1.clear();
        for (int i = 0; i < 3; i++) {
            list1.add(list.get(i));
        }
        for (Train train : list1) {
            Date date = new Date();
            if (date.getTime() >= train.getStarttime().getTime() && date.getTime() <= train.getEndtime().getTime()) {
                train.setState("进行中");
            } else if (date.getTime() < train.getStarttime().getTime()) {
                train.setState("未开始");
            } else if (date.getTime() > train.getEndtime().getTime()) {
                train.setState("已结束");
            }
            String[] split = train.getCid().split(",");
            train.setCount(split.length);
            Integer quiz = trainMapper.findQuiz(train.getId());
            train.setQuiz(quiz);
        }
        return list1;
    }

    @Override
    public List<Quiz> quizList() {
        List<Quiz> list1 = new ArrayList<>();
        LambdaQueryWrapper<Quiz> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Quiz::getId);
        List<Quiz> list = quizMapper.selectList(lambdaQueryWrapper);
        list1.clear();
        for (int i = 0; i < 3; i++) {
            list1.add(list.get(i));
        }
        for (Quiz quiz : list1) {
            Integer q = quizMapper.findQuiz(quiz.getId());
            quiz.setCount(q);
            if (StringUtils.isEmpty(quiz.getCid()) || quiz.getCid().equals("")) {
                quiz.setNum(0);
            } else {
                String[] split = quiz.getCid().split(",");
                quiz.setNum(split.length);
            }
        }
        return list1;
    }

    @Override
    public Page<Course> findPage(Integer page, Integer pageSize, Course course) {
        Page<Course> page1 = new Page<>(page, pageSize);
        if (course.getLids() != null && !course.getLids().isEmpty()) {
            courseMapper.findPage(page1, course);
            List<Course> list1 = new ArrayList<>();
            List<Course> list = courseMapper.selectList(null);
            for (Course course1 : list) {
                String[] split = course1.getLid().split(",");
                for (int i = 0; i < split.length; i++) {
                    for (int j = 0; j < course.getLids().size(); j++) {
                        if (split[i].equals(course.getLids().get(j) + "")) {
                            list1.add(course1);
                        }
                    }
                }
            }
            List<Course> courseList = list1.stream().distinct().collect(Collectors.toList());
            page1.setRecords(courseList);
            page1.setTotal(courseList.size());
        } else {
            courseMapper.findPage(page1, course);
        }
        return page1;
    }

    @Override
    public List<Label> labelFindAll() {
        return labelMapper.selectList(null);
    }

    @Override
    public String selectLable(Integer s) {
        LambdaQueryWrapper<Label> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Label::getId, s);
        Label label = labelMapper.selectOne(lambdaQueryWrapper);
        return label.getLname();
    }

    @Override
    public List<Catalog> catalog(Integer id, Integer ids) {
        LambdaQueryWrapper<CatalogUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CatalogUser::getCourseId, id);
        List<CatalogUser> one = catalogUserMapper.selectList(lambdaQueryWrapper);
        CatalogUser catalogUser = new CatalogUser();
        for (int i = 0; i < one.size(); i++) {
            if (one.get(i).getUserId() == ids) {
                catalogUser.setCatalogId(one.get(i).getCatalogId());
                catalogUser.setCatalogPid(one.get(i).getCatalogPid());
            }
        }
        String[] split = catalogUser.getCatalogId().split(",");
        List<Catalog> list = new ArrayList<>();
        list.clear();
        for (int i = 0; i < split.length; i++) {
            Catalog one1 = catalogMapper.findOne(Integer.valueOf(split[i]));
            list.add(one1);
        }
        List<Catalog> list2 = catalogMapper.selectList(null);
        List<Catalog> list1 = list.stream().filter(catalog -> {
            return catalog.getPid() == 0;
        }).map(b -> {
            b.setChildren(Child(b.getId(), list2));
            return b;
        }).collect(Collectors.toList());
        String[] split1 = catalogUser.getCatalogPid().split(",");
        for (Catalog catalog : list1) {
            List<Catalog> list3 = catalog.getChildren();
            for (Catalog catalog1 : list3) {
                for (int i = 0; i < split1.length; i++) {
                    if (catalog1.getId() == Integer.valueOf(split1[i])) {
                        catalog1.setState("√");
                    }
                }
            }
        }
        return list1;
    }

    @Override
    public Integer toJinDu(Integer id, Integer ids) {
        LambdaQueryWrapper<CatalogUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CatalogUser::getCourseId, id);
        List<CatalogUser> one = catalogUserMapper.selectList(lambdaQueryWrapper);
        CatalogUser catalogUser = new CatalogUser();
        for (int i = 0; i < one.size(); i++) {
            if (one.get(i).getUserId() == ids) {
                catalogUser.setCatalogId(one.get(i).getCatalogId());
                catalogUser.setCatalogPid(one.get(i).getCatalogPid());
            }
        }
        String[] split = catalogUser.getCatalogId().split(",");
        Double a = 0.0;
        for (int i = 0; i < split.length; i++) {
            Catalog one1 = catalogMapper.findOne(Integer.valueOf(split[i]));
            Integer b = catalogMapper.showCount(one1.getId());
            a = a + b;
        }
        String[] split1 = catalogUser.getCatalogPid().split(",");
        return (int) (split1.length / a * 100);
    }

    @Override
    public List<Catalog> cataloG(Integer id, Integer ids, Integer idss) {
        LambdaQueryWrapper<CatalogUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(CatalogUser::getCourseId, id);
        List<CatalogUser> one = catalogUserMapper.selectList(lambdaQueryWrapper);
        CatalogUser catalogUser = new CatalogUser();
        for (int i = 0; i < one.size(); i++) {
            if (one.get(i).getUserId() == ids) {
                catalogUser.setCatalogId(one.get(i).getCatalogId());
                catalogUser.setCatalogPid(one.get(i).getCatalogPid());
            }
        }
        String[] split = catalogUser.getCatalogId().split(",");
        List<Catalog> list = new ArrayList<>();
        list.clear();
        for (int i = 0; i < split.length; i++) {
            Catalog one1 = catalogMapper.findOne(Integer.valueOf(split[i]));
            list.add(one1);
        }
        List<Catalog> list2 = catalogMapper.selectList(null);
        List<Catalog> list1 = list.stream().filter(catalog -> {
            return catalog.getPid() == 0;
        }).map(b -> {
            b.setChildren(Child(b.getId(), list2));
            return b;
        }).collect(Collectors.toList());
        String[] split1 = catalogUser.getCatalogPid().split(",");
        catalogUser.setCatalogPid(catalogUser.getCatalogPid() + "," + idss);
        for (Catalog catalog : list1) {
            List<Catalog> list3 = catalog.getChildren();
            for (Catalog catalog1 : list3) {
                for (int i = 0; i < split1.length; i++) {
                    if (catalog1.getId() == Integer.valueOf(split1[i])) {
                        catalog1.setState("√");
                    }
                }
            }
        }
        return list1;
    }

    private List<Catalog> Child(Integer id, List<Catalog> list) {
        List list1 = list.stream().filter(catalog -> {
            return catalog.getPid() == id;
        }).map(b -> {
            b.setChildren(Child(b.getId(), list));
            return b;
        }).collect(Collectors.toList());
        return list1;
    }

    @Override
    public PageInfo<Race> raceFindPage(Integer page, Integer pageSize, Race race) {
        PageHelper.startPage(page, pageSize);
        LambdaQueryWrapper<Race> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(race.getRname()) && !race.getRname().equals("")) {
            lambdaQueryWrapper.like(Race::getRname, race.getRname());
        }
        if (race.getStatus() != null) {
            lambdaQueryWrapper.eq(Race::getStatus, race.getStatus());
        }
        if (race.getLids().isEmpty()) {
            List<Race> list2 = raceMapper.selectList(lambdaQueryWrapper);
            for (Race race1 : list2) {
                Date date = new Date();
                if (date.getTime() >= race1.getStarttime().getTime() && date.getTime() <= race1.getEndtime().getTime()) {
                    race1.setState("进行中");
                } else if (date.getTime() < race1.getStarttime().getTime()) {
                    race1.setState("报名中");
                } else if (date.getTime() > race1.getEndtime().getTime()) {
                    race1.setState("已结束");
                }
            }
            return new PageInfo<>(list2);
        } else {
            List<Race> list = raceMapper.selectList(null);
            List<Race> list1 = new ArrayList<>();
            list1.clear();
            for (Race race1 : list) {
                String[] split = race1.getLid().split(",");
                for (int i = 0; i < race.getLids().size(); i++) {
                    for (int j = 0; j < split.length; j++) {
                        if (race.getLids().get(i) == Integer.valueOf(split[j])) {
                            list1.add(race1);
                        }
                    }
                }
            }
            for (Race race1 : list1) {
                Date date = new Date();
                if (date.getTime() >= race1.getStarttime().getTime() && date.getTime() <= race1.getEndtime().getTime()) {
                    race1.setState("进行中");
                } else if (date.getTime() < race1.getStarttime().getTime()) {
                    race1.setState("报名中");
                } else if (date.getTime() > race1.getEndtime().getTime()) {
                    race1.setState("已结束");
                }
            }
            List<Race> collect = list1.stream().distinct().collect(Collectors.toList());
            return new PageInfo<>(collect);
        }
    }

    @Override
    public RaceUser Bao(Integer id, Integer uid) {
        LambdaQueryWrapper<RaceUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RaceUser::getRid, id);
        RaceUser one = raceUserMapper.selectOne(lambdaQueryWrapper);
        if (one != null) {
            if (one.getUid() != null) {
                String[] split = one.getUid().split(",");
                for (int i = 0; i < split.length; i++) {
                    if (uid == Integer.valueOf(split[i])) {
                        return one;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public List<Team> findTeam() {
        return teamMapper.selectList(null);
    }

    @Override
    public List<String> findContestant(Integer rid, Integer tid) {
        LambdaQueryWrapper<RaceUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RaceUser::getRid, rid);
        lambdaQueryWrapper.eq(RaceUser::getTid, tid);
        RaceUser one = raceUserMapper.selectOne(lambdaQueryWrapper);
        String[] split = one.getUid().split(",");
        ArrayList<String> list = new ArrayList<>();
        List<User> list1 = userMapper.selectList(null);
        for (User user : list1) {
            for (String s : split) {
                if (user.getId() == Integer.valueOf(s)) {
                    list.add(user.getUsername());
                }
            }
        }
        return list;
    }

    @Override
    public List<Quiz> findQuiz(Integer id) {
        LambdaQueryWrapper<Quiz> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Quiz::getTid, 1);
        List<Quiz> list = quizMapper.selectList(lambdaQueryWrapper);
        LambdaQueryWrapper<RaceInfo> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(RaceInfo::getRid, id);
        List<RaceInfo> list1 = raceInfoMapper.selectList(lambdaQueryWrapper1);
        ArrayList<Quiz> list2 = new ArrayList<>();
        for (RaceInfo raceInfo : list1) {
            for (Quiz quiz : list) {
                if (raceInfo.getQid() == quiz.getId()) {
                    list2.add(quiz);
                }
            }
        }
        List<QuizPaper> list3 = quizPaperMapper.selectList(null);
        for (QuizPaper quizPaper : list3) {
            for (Quiz quiz : list2) {
                if (quiz.getId() == quizPaper.getQid()) {
                    Integer count = quizPaperMapper.findCount(quiz.getId());
                    quiz.setCount(count);
                    List<Paper> all = paperMapper.findAll(quiz.getId());
                    quiz.setPaper(all);
                }
            }
        }
        return list2;
    }

    @Override
    public PaperUser findPaper(PaperUser paperUser) {
        LambdaQueryWrapper<PaperUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaperUser::getPid,paperUser.getPid());
        lambdaQueryWrapper.eq(PaperUser::getUid,paperUser.getUid());
        lambdaQueryWrapper.eq(PaperUser::getQid,paperUser.getQid());
        return paperUserMapper.selectOne(lambdaQueryWrapper);
    }

    @Override
    public PaperUser findScore(PaperUser paperUser) {
        PaperUser user1 = new PaperUser();
        ArrayList<Integer> list1 = new ArrayList<>();
        ArrayList<Integer> list2 = new ArrayList<>();
        LambdaQueryWrapper<PaperUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaperUser::getUid,paperUser.getUid());
        lambdaQueryWrapper.eq(PaperUser::getQid,paperUser.getQid());
        List<PaperUser> list = paperUserMapper.selectList(lambdaQueryWrapper);
        Integer a=0;
        Integer b=0;
        Integer c=0;
        Integer d=0;
        for (int i = 0; i < list.size(); i++) {
            PaperUser user = list.get(i);
            LambdaQueryWrapper<Paper> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(Paper::getId, user.getPid());
            Paper paper = paperMapper.selectOne(lambdaQueryWrapper1);
            if (paper.getOpt().equals(user.getInfo())) {
                a = a + 1;
                c = i + 1;
                list1.add(c);
            } else {
                b = b + 1;
                d = i + 1;
                list2.add(d);
            }
        }
        Double e=(double)a/(a+b)*100;
        user1.setCount1(e.intValue());
        user1.setCount2(a);
        user1.setCount3(b);
        user1.setPaper1(list1);
        user1.setPaper2(list2);
        Rankings rankings = new Rankings();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId,paperUser.getUid());
        User user = userMapper.selectOne(userLambdaQueryWrapper);
        rankings.setScore(e.intValue());
        rankings.setName(user.getUsername());
        rankings.setQid(paperUser.getQid());
        LambdaQueryWrapper<Rankings> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(Rankings::getName,rankings.getName());
        lambdaQueryWrapper1.eq(Rankings::getQid,rankings.getQid());
        Rankings one = rankingsMapper.selectOne(lambdaQueryWrapper1);
        if (one==null){
            rankingsMapper.insert(rankings);
        }
        return user1;
    }

    @Override
    public List<Rankings> toRankings(Integer qid) {
        LambdaQueryWrapper<Rankings> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Rankings::getQid,qid).orderByDesc(Rankings::getScore);
       return rankingsMapper.selectList(lambdaQueryWrapper);
    }
}
